import pymssql

from DBUtils.PooledDB import PooledDB
from common.db.dbconfigs import *

'''
sql:将要执行的sql. 如果以select开头,有返回值;
config:将要连接的数据库,如果为空默认连接zl
'''

# 数据库连接池
db_pools = {}


def execute(sql, config, dictionary=False, connection=None, autocommit=True):
    if not connection:
        connection = _connection(config)

    results = _execute(sql, connection, dictionary)
    if autocommit:
        connection.commit()
    return results


def _connection(config):
    pool_key = str(config)
    if pool_key not in db_pools:
        pool = PooledDB(creator=pymssql, mincached=1, maxcached=2, maxconnections=4, blocking=True,
                        server=config["server"],
                        user=config["user"],
                        password=config["password"],
                        database=config["database"], )
        db_pools[pool_key] = pool
    return db_pools[pool_key].connection()


def _execute(sql, connection, dictionary=False):
    cursor = connection.cursor(as_dict=dictionary)

    cursor.execute(sql)
    results = None
    if sql.lstrip().upper().startswith("SELECT"):
        results = cursor.fetchall()
    cursor.close()
    return results
